/*
  Copyright (C) 2008 Toshiaki Maki <makingx@gmail.com>
  All rights reserved.
  
  Redistribution and use in source and binary forms, with or without modification,
  are permitted provided that the following conditions are met:
  
  1. Redistributions of source code must retain the above copyright notice,
     this list of conditions and the following disclaimer.
  2. Redistributions in binary form must reproduce the above copyright notice,
     this list of conditions and the following disclaimer in the documentation
     and/or other materials provided with the distribution.
  3. The name of the author may not be used to endorse or promote products derived
     from this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
  INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
  OF SUCH DAMAGE.
*/

/* -*- coding:utf-8-unix -*- */
#include "BlackPine.h"
#include <boost/regex.hpp>
#include <boost/tokenizer.hpp>
#define VAR_MARK '$'
#define ESC_MARK '#'
#define PLG_MARK '!'
#define PLG_ARG_SEP ' '
#define PLG_ARG_ESC '\\'
#define PLG_ARG_QUOTE '`'
#define INC_TAG "include"
#define TIME_TAG "time"
#define LD_TAG "LD"
#define RD_TAG "RD"
#define VER_TAG "BP_VERSION"
#ifndef BP_VERSION
#define BP_VERSION "????"
#endif

static std::string escapeHtml(const std::string& s) 
{
  std::string ret;
  for (size_t i = 0; i < s.size(); ++i) {
    unsigned char c = s[i];
    if (c == '&') ret += "&amp;";
    else if (c == '<') ret += "&lt;";
    else if (c == '>') ret += "&gt;";
    else if (c == '\'') ret += "&#39;";
    else if (c == '"') ret += "&quot;";
    else ret += c;
  }
  return ret;
}

static void escapeRegex(std::string& ret, const std::string& str)
{
  ret = str;
  for (std::size_t i = 0; i < str.size(); ++i) {
    switch (str[i]) {
    case '.' :
    case '|' :
    case '*' :
    case '?' :
    case '+' :
    case '(' :
    case ')' :
    case '{' :
    case '}' :
    case '[' :
    case ']' :
    case '^' :
    case '$' :
    case '\\' :
    case '-' :
      ret.insert(i, 1, '\\');
      break;
    default :
      break;
    }
  }
}

// static std::string escapeString(const std::string& str)
// {
//   std::string ret;
//   for (size_t i = 0; i < str.size(); ++i)
//     if (str[i] == '"') ret += "\\\"";
//     else ret += str[i];
//   return ret;
// }  

BlackPine::~BlackPine()
{
  for (std::map<std::string, BlackPinePlugin*>::iterator it = plugins.begin(); it != plugins.end(); ++it) {
    if (it->second != NULL) {
      delete_plugin(it->second);
    }
  }
  
  for (string_map::iterator it = variable.begin(); it != variable.end(); ++it) {
    if (it->second != NULL) {
      delete it->second;
    }
  }

  for (string_map::iterator it = to_string_map.begin(); it != to_string_map.end(); ++it) {
    if (it->second != NULL) {
      delete it->second;
    }
  }
}

void BlackPine::parse(std::ostream& strm, const std::string& str) 
{
  std::string lde, rde;
  escapeRegex(lde, left_delimiter);
  escapeRegex(rde, right_delimiter);
  std::string regex = lde + "([^" + lde + "]+)" + rde;
  boost::regex  r(regex);
  size_t pos = 0;
  for (boost::sregex_iterator it(str.begin(), str.end(), r), end; it != end; ++it) {
    strm << str.substr(pos, it->position() - pos);
    expandValue(strm, it->str(1));
    pos = it->position() + it->str().size();
  }
  strm << str.substr(pos);
}

void BlackPine::expandValue(std::ostream& strm, const std::string& str)
{
  switch (str[0]) {
  case VAR_MARK : 
    {
      std::string key = str.substr(1);
      strm << getValue(key);
      break;
    } 
  case ESC_MARK : 
    {
      std::string key = str.substr(1);
      strm << escapeHtml(getValue(key));
      break;
    }
  case PLG_MARK : 
    {
      std::stringstream body(str.substr(1));      
      std::string pname;
      size_t psize;
      body >> pname;
      psize = pname.size();
      pname += "Plugin";
      if (plugins.find(pname) == plugins.end()) {
	BlackPinePlugin* p = new_plugin(pname.c_str(), plugin_dir.c_str());
	if (p) {
	  plugins.insert(make_pair(pname, p));
	} else {
	  break;
	}
      }

      std::string tmp;
      std::vector<std::string> args;
      if (body >> tmp) {
	boost::escaped_list_separator<char> esc(PLG_ARG_ESC, PLG_ARG_SEP, PLG_ARG_QUOTE);
	boost::tokenizer<boost::escaped_list_separator<char> > tokens(body.str().substr(psize+1), esc);
	for (boost::tokenizer<boost::escaped_list_separator<char> >::iterator it = tokens.begin(); 
	     it != tokens.end(); ++it) {
	  if (!it->empty()) {
	    switch ((*it)[0]) {
	    case VAR_MARK:
	      args.push_back(getValue(it->substr(1)));
	      break;
	    case ESC_MARK:
	      args.push_back(escapeHtml(getValue(it->substr(1))));
	      break;
	    default :
	      args.push_back(*it);
	      break;
	    }
	  }
	}
	if (args.size() == 1 && tmp[0] != PLG_ARG_QUOTE) {
	  /* escape bug when tokens have no space */
	  args[0] = body.str().substr(psize+1);
	}
      }
      std::ostringstream rets("");
      plugins[pname]->process(rets, args);
      if (!rets.str().empty()) strm << rets.str();
      break;
    }
  default : 
    {
      std::stringstream body(str);
      std::string tag;
      body >> tag;
      if (tag == INC_TAG) {	
	std::string fname;
	body >> fname;
	expand(strm, fname.c_str());
      } else if (tag == TIME_TAG) {
	strm << (getTime() - start_time);
      } else if (tag == LD_TAG) {
	strm << left_delimiter;
      } else if (tag == RD_TAG) {
	strm << right_delimiter;
      } else if (tag == VER_TAG) {
	strm << BP_VERSION;
      } else {
	strm << "UNDIFINED TAG >> " << tag;
      }
      break;
    }
  }
}

void BlackPine::expand(std::ostream& strm, std::istream& is) 
{
  is.clear();
  is.seekg (0, std::ios::beg);
  std::string line;
#if 1
  std::stringstream ss;
  while (getline(is, line)) {
    ss << line << std::endl;
  }
  parse(strm, ss.str());
#else
  while (getline(is, line)) {
    parse(strm, line);
    strm << std::endl;
  }
#endif
}

void BlackPine::expand(std::ostream& strm, const char* fname)
{  
  std::string f = template_dir;
  if (f[f.size()-1] != '/') f += "/"; 
  f += fname;
  std::ifstream is(f.c_str());
  if (is.is_open()) {
    expand(strm, is);
    is.close();
  } else {
    strm << "<span style=\"color:red\"> can't open : " <<  escapeHtml(f) << "!</span>";
  }
}

void BlackPine::loadConfig(const char* fname) {
  std::ifstream fs(fname);
  std::string line;
  if (fs.is_open()) {
    while (getline(fs, line)) {
      std::istringstream ss(line);
      setConfig(ss);
    }
  }
}


void BlackPine::setConfig(std::istringstream& strm)
{
  std::string key, value;
  strm >> key;
  if (key == ":assign" || key == ":include") {
    std::string k, v;
    std::string* s;
    while (strm >> k) {
      if (strm >> v) {
	s = new std::string((key == ":include") ? toString(v.c_str()) : v);
	if (k[0] == VAR_MARK) variable.insert(make_pair(k.substr(1).c_str(), s));
	else if (k[0] == ESC_MARK) {
	  std::string* e = new std::string(escapeHtml(*s));
	  variable.insert(make_pair(k.substr(1).c_str(), e));
	  delete s;
	}
      }
    }
  } else if (key == ":template_dir") {
    if (strm >> value)  template_dir = value;
  } else if (key == ":compile_dir") {
    if (strm >> value) compile_dir = value;
  } else if (key == ":plugin_dir") {
    if (strm >> value) plugin_dir = value;
  } else if (key == ":left_delimiter") {
    if (strm >> value) left_delimiter = value;
  } else if (key == ":right_delimiter") {
    if (strm >> value) right_delimiter = value;
  }
}

#ifdef HAVE_MAIN

int main ()
{
  BlackPine bp;
  //  char* tpl = "layout.bp";  
  char* tpl = "test.bp";  
  bp.setTemplateDir("./template/");  
  bp.setPluginDir("./plugins/");  
  //  bp.loadConfig("bpconf");

  char fname[strlen(bp.getTemplateDir()) + strlen(tpl) + 1];

  bp.assign("foo", "Hello World!");
  bp.assign("bar", "<a href=\"/\">BlackPine</a>");
  std::cerr << "=== TEMPLATE ===" << std::endl;
  sprintf(fname, "%s%s", bp.getTemplateDir(), tpl);
  std::cerr << fname << std::endl;
  std::cerr << "=== OUTPUT ===" << std::endl;
  //  bp.display(tpl);
  std::cerr << bp.toString(tpl) << std::endl;
}
#endif
